package com.difsonapps.android.marker.activities;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.JsonObjectRequest;
import com.difsonapps.android.marker.AppConstant;
import com.difsonapps.android.marker.CustomRequest;
import com.difsonapps.android.marker.FeedActivity;
import com.difsonapps.android.marker.FormPhotoActivity;
import com.difsonapps.android.marker.MainActivity;
import com.difsonapps.android.marker.R;
import com.difsonapps.android.marker.R.id;
import com.difsonapps.android.marker.R.layout;
import com.difsonapps.android.marker.R.menu;
import com.difsonapps.android.marker.R.string;
import com.difsonapps.android.marker.UserConnected;
import com.difsonapps.android.marker.app.AppController;
import com.difsonapps.android.marker.beans.FeedItem;
import com.difsonapps.android.marker.beans.PhotoUpload;
import com.difsonapps.android.marker.beans.User;
import com.difsonapps.android.marker.services.AccountAuthenticator;
import com.difsonapps.android.marker.services.InviteFacebookFriendsIntentService;
import com.difsonapps.android.marker.util.MarkerUtil;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.Session.StatusCallback;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.listeners.OnLoginListener;
import com.sromku.simple.fb.listeners.OnProfileListener;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.transition.Visibility;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends AccountAuthenticatorActivity {
    static final String PENDING_REQUEST_BUNDLE_KEY = "com.difsonapps.android.marker:PendingRequest";
    Session session;
    boolean pendingRequest;
    
	SimpleFacebook mSimpleFacebook;
	private final int VALIDATE_ACCOUNT = 1;
    private static final String TAG = LoginActivity.class.getSimpleName();
    protected boolean auth_automatically = false;
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private static final String[] DUMMY_CREDENTIALS = new String[] {"foo@example.com:hello", "bar@example.com:world" };
	String authenticationOrigin = "";
	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.difsonapps.android.marker.extra.EMAIL";

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private TextView errorTextView;
	
	private Facebook facebook;
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;

	ProgressDialog loadingProgressDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		authenticationOrigin = getIntent().getStringExtra(AccountAuthenticator.KEY_AUTHENTICATION_ORIGIN);
		if(authenticationOrigin==null) authenticationOrigin = "";
		setContentView(R.layout.activity_login);
		//getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1F89CA")));
		getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.main_color)));
		
		facebook = new Facebook(getResources().getString(R.string.app_id));
        mAsyncRunner = new AsyncFacebookRunner(facebook);

        errorTextView = (TextView) findViewById(R.id.errorTextView);
		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							login();
							//attemptLogin();
							return true;
						}
						return false;
					}
				});
		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
        // Listening to register new account link
        registerScreen.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View v) {
                btnRegisterClick(v);
            }
        });
		/*mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		loginErrorView = (TextView) findViewById(R.id.loginError);*/

		
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		//Check if the user is not already connected
		if(auth_automatically) load();
		//else showProgress(false);
		
		//New facebook
        this.session = createSession();
        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
	}
	


	public void btnLoginClick(View v){
		login();
	}
	public void btnLoginFacebookClick(View v){
		if(true){
			if (this.session.isOpened()) {
				pendingRequest = false;
	            sendRequests();
	        } else {
	            pendingRequest = true;
	            this.session.openForRead(new Session.OpenRequest(this).setCallback(callback));
	        }
			//mSimpleFacebook.login(onLoginListener);
			//if(mSimpleFacebook.isLogin()) getProfileFcbk();
			//else mSimpleFacebook.login(onLoginListener);
			return;
		}
		mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("facebook_access_token", null);
	    long expires = mPrefs.getLong("facebook_access_expires", 0);
	    Log.d("Access Token", access_token);
	    Log.d("expires Token", ""+expires);
	    if (access_token != null) {
	        facebook.setAccessToken(access_token);
	    }
	 
	    if (expires != 0) {
	        facebook.setAccessExpires(expires);
	    }
	 
	    if (!facebook.isSessionValid()) {
	        facebook.authorize(this,
	                new String[] { "email", "publish_stream" },
	                new Facebook.DialogListener() {
	                    @Override
	                    public void onCancel() {
	                        // Function to handle cancel event
	                    }
	 
	                    @Override
	                    public void onComplete(Bundle values) {
	                        // Function to handle complete event
	                        // Edit Preferences and update facebook acess_token
	                        Log.d("Facebook Token", facebook.getAccessToken());
	                        Log.d("Facebook expire", ""+facebook.getAccessExpires());
	                        
	                    	SharedPreferences.Editor editor = mPrefs.edit();
	                        editor.putString("facebook_access_token", facebook.getAccessToken());
	                        editor.putLong("facebook_access_expires", facebook.getAccessExpires());
	                        editor.commit();
	                        getProfileInformation(true);
	                        getPhoto(true);
	                    }
	 
	                    @Override
	                    public void onError(DialogError error) {
	                        // Function to handle error
	 
	                    }
	 
	                    @Override
	                    public void onFacebookError(FacebookError fberror) {
	                        // Function to handle Facebook errors
	 
	                    }
	 
	                });
	    }else{
	    	//user is already auth
	    	Log.d("MD5", MarkerUtil.md5("test"));
	    	toast("Already log in");
	    	getProfileInformation(true);
	    	getPhoto(true);
	    }
	}
	JSONObject profileFbJson;
	String facebookPicture = "";
	public void getProfileInformation(final boolean login) {
	    mAsyncRunner.request("me", new AsyncFacebookRunner.RequestListener() {
	        @Override
	        public void onComplete(String response, Object state) {
	        	Log.d("Profile", response);
	            //toast("Here");
	            String json = response;
	            try {
	                JSONObject profile = new JSONObject(json);
	                profileFbJson = profile;
	                // getting name of the user
	                final String name = profile.getString("name");
	                // getting email of the user
	                final String email = profile.getString("email");
	                
	 
	                runOnUiThread(new Runnable() {
	 
	                    @Override
	                    public void run() {
	                    	try {
	                    		if(login) loginFb();
	                    	} catch (JSONException e) {
	        	                e.printStackTrace();
	        	            }
	                        Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
	                    }
	 
	                });
	 
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
	        }
	 
	        @Override
	        public void onIOException(IOException e, Object state) {
	        	toast("IO Exception");
	        }
	 
	        @Override
	        public void onFileNotFoundException(FileNotFoundException e,
	                Object state) {
	        	toast("File not found Exception");
	        }
	 
	        @Override
	        public void onMalformedURLException(MalformedURLException e,
	                Object state) {
	        	toast("onMalformedURLException");
	        }
	 
	        @Override
	        public void onFacebookError(FacebookError e, Object state) {
	        	toast("onFacebookError");
	        }
	    });
	}
	public void getPhoto(final boolean login) {
		if(true) return;
	    mAsyncRunner.request("me/picture", new AsyncFacebookRunner.RequestListener() {
	        @Override
	        public void onComplete(String response, Object state) {
	            Log.d("Photo", response);
	            if(true) return;
	            //toast("Here");
	            String json = response;
	            try {
	                JSONObject picture = new JSONObject(json);
	                if(picture.has("data")){
	                	JSONObject data = picture.getJSONObject("data");
	                	if(data.has("url")) facebookPicture = data.getString("url");
	                }
	                runOnUiThread(new Runnable() {
	 
	                    @Override
	                    public void run() {
	                    	toast("Photo "+facebookPicture);
	                    	try {
	                    		if(login) loginFb();
	                    	} catch (JSONException e) {
	        	                e.printStackTrace();
	        	            }
	                    }
	 
	                });
	 
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
	        }
	 
	        @Override
	        public void onIOException(IOException e, Object state) {
	        	toast("IO Exception");
	        }
	 
	        @Override
	        public void onFileNotFoundException(FileNotFoundException e,
	                Object state) {
	        	toast("File not found Exception");
	        }
	 
	        @Override
	        public void onMalformedURLException(MalformedURLException e,
	                Object state) {
	        	toast("onMalformedURLException");
	        }
	 
	        @Override
	        public void onFacebookError(FacebookError e, Object state) {
	        	toast("onFacebookError");
	        }
	    });
	}
	public void btnGetUserClick(View v){
		getCurrentUser();
	}
	public void btnRegisterClick(View v){
		Intent intent = new Intent(this, RegisterActivity.class);
        startActivityForResult(intent, VALIDATE_ACCOUNT);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}
	public void onResume() {
	    super.onResume();
	    //mSimpleFacebook = SimpleFacebook.getInstance(this);
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (this.session.onActivityResult(this, requestCode, resultCode, data) &&
                pendingRequest &&
                this.session.getState().isOpened()) {
            sendRequests();
        } 
	    //mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data); 
        
        switch(requestCode) { 
        case VALIDATE_ACCOUNT:
            if(resultCode == RESULT_OK){
				try {
					User user = data.getParcelableExtra(RegisterActivity.EXTRA_USER);
					boolean auth = data.getBooleanExtra(RegisterActivity.EXTRA_AUTH, false);
					if(user!=null && auth){
						confirmLogin(user);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
 
            }
            break;
        }
    }
	

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        pendingRequest = savedInstanceState.getBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putBoolean(PENDING_REQUEST_BUNDLE_KEY, pendingRequest);
    }
	
    public void load(){
    	//mLoginStatusMessageView.setText(R.string.loading);
		//showProgress(true);
    	loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		getCurrentUser();
    }
    
	public void login() {
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
    	
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();
		Map<String, String> params = new HashMap<String, String>();
        params.put("email", mEmail);
        params.put("password", MarkerUtil.md5(mPassword));
        
        loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.authUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonAuth(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	showProgress(false);
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
    
	OnLoginListener onLoginListener = new OnLoginListener() {
	    @Override
	    public void onLogin() {
	    	getProfileFcbk();
	    }

	    @Override
	    public void onNotAcceptingPermissions(Permission.Type type) {
	        Log.w(TAG, String.format("You didn't accept %s permissions", type.name()));
	    }

		@Override
		public void onThinking() {
		}

		@Override
		public void onException(Throwable throwable) {
		}

		@Override
		public void onFail(String reason) {
		}
	};
	
	private void getProfileFcbk(){
		toast("Getting user profile");
		mSimpleFacebook.getProfile(onProfileListener);
	}
	
	OnProfileListener onProfileListener = new OnProfileListener() {         
	    @Override
	    public void onComplete(Profile profile) {
	        try {
	        	toast("Profile received... : "+profile.getName());
	        	//toast("Profile picture "+profile.getPicture());
				loginFb(profile);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	Log.i(TAG, "My profile id = " + profile.getId());
	    }
	};
	
	public void loginFb(com.facebook.model.GraphUser profile) throws JSONException {
		toast("Login facebook");
		String email = profile.getProperty("email").toString();
		Boolean verified = (Boolean)profile.getProperty("verified");
		String gender = profile.getProperty("gender").toString();
		String locale = profile.getProperty("locale").toString();
		String timezone = profile.getProperty("timezone").toString();
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", profile.getId());
        params.put("email", email);
        params.put("firstname", profile.getFirstName());
        params.put("lastname", profile.getLastName());
        params.put("sex", gender);
        params.put("link", profile.getLink());
        params.put("locale", locale);
        params.put("timezone", timezone);
        params.put("username", profile.getUsername());
        params.put("verified", verified?"1":"0");
        params.put("picwithlogo", "https://graph.facebook.com/"+params.get("id")+"/picture");
        toast("Login facebook");
        mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("facebook_access_token", "");
	    long expires = mPrefs.getLong("facebook_access_expires", 0);
	    params.put("facebook_access_token", access_token);
	    params.put("facebook_expire", ""+expires);
	    
	    toast("Login facebook");
        loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.authFbUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonAuthFb(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	showProgress(false);
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	public void loginFb(Profile profile) throws JSONException {
		toast("Login facebook");
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", profile.getId());
        params.put("email", profile.getEmail());
        params.put("firstname", profile.getFirstName());
        params.put("lastname", profile.getLastName());
        params.put("sex", profile.getGender());
        params.put("link", profile.getLink());
        params.put("locale", profile.getLocale());
        params.put("timezone", ""+profile.getTimeZone());
        params.put("username", profile.getUsername());
        params.put("verified", profile.getVerified()?"1":"0");
        //Log.d("Picture", profile.getPicture());
        params.put("picwithlogo", "https://graph.facebook.com/"+params.get("id")+"/picture");
        //params.put("picwithlogo", profile.getPicture());
        toast("Login facebook");
        mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("facebook_access_token", "");
	    long expires = mPrefs.getLong("facebook_access_expires", 0);
	    params.put("facebook_access_token", access_token);
	    params.put("facebook_expire", ""+expires);
	    
	    toast("Login facebook");
        loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.authFbUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonAuthFb(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	showProgress(false);
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	public void loginFb() throws JSONException {
		errorTextView.setText("");
		errorTextView.setVisibility(View.GONE);
		Map<String, String> params = new HashMap<String, String>();
        params.put("id", profileFbJson.has("id")?profileFbJson.getString("id"):"");
        params.put("email", profileFbJson.has("email")?profileFbJson.getString("email"):"");
        params.put("firstname", profileFbJson.has("first_name")?profileFbJson.getString("first_name"):"");
        params.put("lastname", profileFbJson.has("last_name")?profileFbJson.getString("last_name"):"");
        params.put("sex", profileFbJson.has("gender")?profileFbJson.getString("gender"):"");
        params.put("link", profileFbJson.has("link")?profileFbJson.getString("link"):"");
        params.put("locale", profileFbJson.has("locale")?profileFbJson.getString("locale"):"");
        params.put("timezone", profileFbJson.has("timezone")?""+profileFbJson.getInt("timezone"):"");
        params.put("username", profileFbJson.has("username")?profileFbJson.getString("username"):"");
        params.put("verified", profileFbJson.has("verified")?(profileFbJson.getBoolean("verified")?"1":"0"):"");
        params.put("email", profileFbJson.has("email")?profileFbJson.getString("email"):"");
        params.put("picwithlogo", "https://graph.facebook.com/"+params.get("id")+"/picture");
        
        mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("facebook_access_token", "");
	    long expires = mPrefs.getLong("facebook_access_expires", 0);
	    params.put("facebook_access_token", access_token);
	    params.put("facebook_expire", ""+expires);
	    
        
        loadingProgressDialog = ProgressDialog.show(this, getResources().getString(R.string.loading), getResources().getString(R.string.loading), true);
        loadingProgressDialog.setCancelable(true);
		
		CustomRequest jsObjRequest = new CustomRequest(
				Method.POST, 
				AppConstant.authFbUrl, 
				params,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	parseJsonAuthFb(response);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	showProgress(false);
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	private void getCurrentUser(){
		toast("cookie key : "+AppController.getInstance().getCookieKey());
		CustomRequest jsObjRequest = new CustomRequest(
				Method.GET, 
				AppConstant.getUserUrl, 
				null,
				new Response.Listener<JSONObject>() {
					 
                    @Override
                    public void onResponse(JSONObject response) {
                    	//toast("Response : "+response.toString());
                    	parseJsonAuth(response);
                    	//showProgress(false);
                    }
                },
                new Response.ErrorListener() {
 
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	showProgress(false);
                    	toast("Error: " + error.getMessage());
                    }
                }
        );

       AppController.getInstance().addToRequestQueue(jsObjRequest);
	}
	
	
	private void confirmLogin(User user){
		//TODO 
		String accountType = this.getIntent().getStringExtra(AccountAuthenticator.KEY_AUTHTOKEN_TYPE);  
        if (accountType == null) {  
            accountType = AccountAuthenticator.ACCOUNT_TYPE;  
        }
        AccountManager accMgr = AccountManager.get(this);
        //TODO Check first if any account exist in this account type and delete it
        Account[] accounts = accMgr.getAccountsByType(accountType);
        for (Account account : accounts) {
            accMgr.removeAccount(account, null, null);
        }
        
        final Account account = new Account(user.getEmail(), accountType);  
        accMgr.addAccountExplicitly(account, "password here", null);
        if(authenticationOrigin.endsWith(AccountAuthenticator.AUTHENTICATION_SERVICE)){
        	final Intent intent = new Intent();  
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, user.getEmail());  
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);  
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);  
            this.setAccountAuthenticatorResult(intent.getExtras());  
            this.setResult(RESULT_OK, intent);  
            this.finish();
        	return;
        }
        //TODO Add user in the acc
        
		AppConstant.userConnected = user;
    	Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		this.finish();
	}
	
	private void parseJsonAuth(JSONObject response) {
        try {
        	//toast(response.toString());
        	String result_code = response.has("result_code")?response.getString("result_code"):"";
            if(response.has("success")){
            	User user = User.parseFromJsonObject(response);
            	if(user==null){
            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
                	errorTextView.setVisibility(View.VISIBLE);
            		return;
            	}
            	confirmLogin(user);
            }else if(result_code.equals("not_confirm")){
            	User user = User.parseFromJsonObject(response);
            	if(user==null){
            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
                	errorTextView.setVisibility(View.VISIBLE);
            		return;
            	}
            	Intent intent = new Intent(this, RegisterActivity.class);
            	Bundle b = new Bundle();
				b.putParcelable(RegisterActivity.EXTRA_USER, user);
				intent.putExtras(b);
				startActivityForResult(intent, VALIDATE_ACCOUNT);
            }else if(response.has("error")){
            	errorTextView.setText(getResources().getString(R.string.error_authcredentials_invalid));
            	errorTextView.setVisibility(View.VISIBLE);
            	showProgress(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            showProgress(false);
        }
        if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
    }
	
	private void parseJsonAuthFb(JSONObject response) {
        try {
        	Log.d("Auth Fb response", response.toString());
        	//toast(response.toString());
        	String result_code = response.has("result_code")?response.getString("result_code"):"";
        	if(result_code.equals("authenticated")){
        		User user = User.parseFromJsonObject(response);
            	if(user==null){
            		errorTextView.setText(getResources().getString(R.string.an_error_occured));
                	errorTextView.setVisibility(View.VISIBLE);
            		return;
            	}
            	confirmLogin(user);
        	}else if(result_code.equals("not_confirmed")){
        		if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
        		toast("Show confirmation dialog");
        		Intent intent = new Intent(this, ConfirmLoginFacebookActivity.class);
            	Bundle b = new Bundle();
				b.putString(ConfirmLoginFacebookActivity.EXTRA_USERID, profileFbJson.has("id")?profileFbJson.getString("id"):"");
				b.putString(ConfirmLoginFacebookActivity.EXTRA_USERNAME, profileFbJson.has("name")?profileFbJson.getString("name"):"");
				b.putString(ConfirmLoginFacebookActivity.EXTRA_USERPIC, response.has("picture")?response.getString("picture"):"");
				intent.putExtras(b);
				startActivityForResult(intent, VALIDATE_ACCOUNT);
        	}
        	else if(result_code.equals("error")){
        		errorTextView.setText(getResources().getString(R.string.an_error_occured));
            	errorTextView.setVisibility(View.VISIBLE);
            	showProgress(false);
        	}else if(response.has("exception")){
            	errorTextView.setText(response.getString("exception"));
            	errorTextView.setVisibility(View.VISIBLE);
            	showProgress(false);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            showProgress(false);
        }
        if(loadingProgressDialog!=null) loadingProgressDialog.dismiss();
    }
	
	private void toast(String text){
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}



	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		
	}
	
	StatusCallback callback = new StatusCallback() {
        public void call(Session session, SessionState state, Exception exception) {
            if (exception != null) {
                new AlertDialog.Builder(LoginActivity.this)
                        .setTitle(R.string.an_error_occured)
                        .setMessage(exception.getMessage())
                        .setPositiveButton(R.string.ok_button, null)
                        .show();
                LoginActivity.this.session = createSession();
            }
        }
    };
    private Session createSession() {
        Session activeSession = Session.getActiveSession();
        if (activeSession == null || activeSession.getState().isClosed()) {
            activeSession = new Session.Builder(this).setApplicationId(getResources().getString(R.string.app_id)).build();
            Session.setActiveSession(activeSession);
        }
        return activeSession;
    }
    
    private void getHask(){
    	try {
    		PackageInfo info = getPackageManager().getPackageInfo("com.difsonapps.android.marker", PackageManager.GET_SIGNATURES);
    		for (Signature signature : info.signatures) {
    		MessageDigest md = MessageDigest.getInstance("SHA");
    		md.update(signature.toByteArray());
    		String sign=Base64.encodeToString(md.digest(), Base64.DEFAULT);
    		Log.e("MY KEY HASH:", sign);
    		Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show();
    		}
    		} catch (NameNotFoundException e) {
    		} catch (NoSuchAlgorithmException e) {
    		}
    }
    
    private void sendRequests() {
    	//getHask();
    	//if(true) return;
    	
    	toast("Executing request...");
    	com.facebook.Request.executeMeRequestAsync(session, new com.facebook.Request.GraphUserCallback() {

            @Override
            public void onCompleted(com.facebook.model.GraphUser user, com.facebook.Response response) {
                if (user != null) {
                	try {
						loginFb(user);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    //toast("Name : "+user.getName());
                }
            }
        });
    	//TODO Get the current user and sent it on mark it server
    }

}
